1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
| using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI;
public class UIGridRenderer : Graphic { public float thickness; public Vector2Int gridSize; private float width; private float height; private float cellWidth; private float cellHeight;
protected override void OnPopulateMesh(VertexHelper vh) { vh.Clear(); width = rectTransform.rect.width; height = rectTransform.rect.height; cellWidth = width / gridSize.x; cellHeight = height / gridSize.y; int count = 0; for (int y = 0; y < gridSize.y; y++) { for (int x = 0; x < gridSize.x; x++) { DrawCell(vh, x, y, count); count++; } } }
void DrawCell(VertexHelper vh, int x, int y, int index) { float xPos = cellWidth * x; float yPos = cellHeight * y; UIVertex vertex = UIVertex.simpleVert; vertex.color = color;
vertex.position = new Vector3(xPos, yPos); vh.AddVert(vertex); vertex.position = new Vector3(xPos, yPos+cellHeight); vh.AddVert(vertex); vertex.position = new Vector3(xPos+cellWidth, yPos+cellHeight); vh.AddVert(vertex); vertex.position = new Vector3(xPos+cellWidth, yPos); vh.AddVert(vertex);
float widthSqr = thickness * thickness; float distanceSqr = widthSqr / 2f; float distance = Mathf.Sqrt(distanceSqr); vertex.position = new Vector3(xPos+(distance), yPos+(distance)); vh.AddVert(vertex); vertex.position = new Vector3(xPos+(distance), yPos+(cellHeight-distance)); vh.AddVert(vertex); vertex.position = new Vector3(xPos+(cellWidth-distance), yPos+(cellHeight-distance)); vh.AddVert(vertex); vertex.position = new Vector3(xPos+(cellWidth-distance), yPos+(distance)); vh.AddVert(vertex); int offset = index * 8; vh.AddTriangle(offset+0, offset+1,offset+ 5); vh.AddTriangle(offset+5, offset+4, offset+0); vh.AddTriangle(offset+1, offset+2, offset+6); vh.AddTriangle(offset+6, offset+5, offset+1); vh.AddTriangle(offset+2, offset+3, offset+7); vh.AddTriangle(offset+7, offset+6, offset+2); vh.AddTriangle(offset+3, offset+0, offset+4); vh.AddTriangle(offset+4, offset+7, offset+3); } }
|